package com.woniu.controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.woniu.entity.Admin;
import com.woniu.service.AdminService;
import com.woniu.service.OrderService;
import com.woniu.service.UserService;
import com.woniu.utils.BaseController;
import com.woniu.utils.MyPage;

@Controller
@RequestMapping("/auction/Admin")
public class AdminController extends BaseController {
	@Autowired
	private AdminService adminService;

	@Autowired
	private UserService userService;

	@Autowired
	private OrderService orderService;

	@Autowired
	private RestTemplate rest;

	// admin下的动态跳转
	@RequestMapping(value = "/adminiframe/{value}")
	public String switchIframe(@PathVariable("value") String value) {
		return "paipai/adminiframe/" + value;
	}

	// 发送验证码
	// 发送验证码
	@RequestMapping("/sendchecknum")
	public void sendCheckNum(String phone, HttpServletResponse resp, HttpServletRequest req) throws IOException {
		// 清除之前存在session中的的验证码
		System.out.println("后台验证码");
		if (req.getSession().getAttribute("verifyCode") != null) {
			req.getSession().removeAttribute("verifyCode");
		}
		System.out.println("接收验证码的手机号：" + phone);
		// 手机号
		String mobile = phone;
		// 模板id
		int tplId = 188494;
		// 生成验证码
		String checkNum = String.valueOf((int) ((Math.random() * 9 + 1) * 1000));
		// 将生成的验证码放到session中
		req.getSession().setAttribute("verifyCode", checkNum);
		System.out.println("生成的验证码：" + checkNum);
		// 变量名和变量值对，整串值需要urlencode
		String tplValue = "#code#=" + checkNum;
		System.out.println("拼接的tplValue：" + tplValue);
		String tplValueAfterTranslate = URLEncoder.encode(tplValue, "utf-8");
		System.out.println("转换拼接的tplValue：" + tplValueAfterTranslate);
		String key = "ff55f3176ca70a91101a31088836fba8";
		// 生成完整url，格式：http://v.juhe.cn/vercodesms/send.php?key=您申请的key&tplId=1&tplValue=%23code%23%3d12345&mobile=17715888***
		String url = "http://v.juhe.cn/sms/send?key=" + key + "&tpl_id=" + tplId + "&tpl_value="
				+ tplValueAfterTranslate + "&mobile=" + mobile;
		System.out.println("拼接的完整url：" + url);
		// 发送请求
		RestTemplate restTemplate = new RestTemplate();
		Object obj = restTemplate.getForObject(url, Object.class);
		System.out.println("网站返回的数据：" + obj);
		// 将接收到的返回值转化成json
		// String json = JSON.toJSONString(obj);
		// System.out.println("转换为json后：" + json);

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("data", obj);
		String jsonMap = JSON.toJSONString(map);
		System.out.println("转换的jsonMap：" + jsonMap);
		resp.setCharacterEncoding("utf-8");
		resp.getWriter().write(jsonMap);
	}

	// 忘记密码第一步验证
	@RequestMapping("/forgetstepone")
	public void forgetStepOne(String name, String phone, String checkCode, HttpServletRequest req,
			HttpServletResponse resp) throws IOException {
		System.out.println("接收到的name：" + name);
		System.out.println("接收到的phone：" + phone);
		System.out.println("接收到的checkCode：" + checkCode);
		resp.setCharacterEncoding("utf-8");
		// 先取出session中的验证码比对，如果不同，直接对外写，如果相同，下一步
		String checkCodeFromSession = (String) req.getSession().getAttribute("verifyCode");
		// 如果两者不相等,直接返回验证码出错
		if (checkCode == null || "".equals(checkCode) || checkCodeFromSession == null || "".equals(checkCodeFromSession)
				|| !checkCodeFromSession.equals(checkCode)) {
			// 清除session存的验证码
			req.getSession().removeAttribute("verifyCode");
			resp.getWriter().write("100");
		} else {
			// 清除session存的验证码
			req.getSession().removeAttribute("verifyCode");
			// 如果验证码正确，到数据库查，如果能查到，返回1
			int result = adminService.selectAdmin(name, phone);
			if (result != 1) {
				// 查询失败
				resp.getWriter().write("101");
			} else {
				// 查询成功，允许更改
				resp.getWriter().write("1");
			}
		}
	}

	// 忘记密码提交修改
	@RequestMapping("/forgetsteptwo")
	public void forgetStepTwo(HttpServletResponse resp, String name, String phone, String newPassOne, String newPassTwo)
			throws IOException {
		System.out.println("忘记密码第2步：" + name);
		System.out.println("忘记密码第2步：" + phone);
		System.out.println("忘记密码第2步：" + newPassOne);
		System.out.println("忘记密码第2步：" + newPassTwo);
		if (newPassOne.equals(newPassTwo)) {
			// 执行密码修改
			int result = adminService.updateForgetPass(name, phone, newPassTwo);
			if (result == 1) {
				// 成功
				resp.getWriter().write("1");
			} else {
				// 101代码表示修改失败
				resp.getWriter().write("101");
			}
		} else {
			// 两次密码不相等
			resp.getWriter().write("100");
		}

	}

	// forget第一步

	// forget第二步

	// 读取管理员主页的所有数据
	@SuppressWarnings("unchecked")
	@RequestMapping("/mainframedata")
	@ResponseBody
	public HashMap<String, Object> getMainFrameData(HttpServletResponse resp) throws IOException {
		System.out.println("getMainFrameData方法执行");
		// 定义总的集合，用于封装所有子结果集合
		// List totalList = new ArrayList();
		// map的方式
		resp.setCharacterEncoding("utf-8");
		Map<String, Object> totalMap = new HashMap<String, Object>();

		/*
		 * 注册用户数 较昨日变动 累计成交金额 较昨日变动 累计成交商品数 较昨日变动
		 */
		// 注册用户数
		Integer userCount = userService.getUserCount();
		System.out.println("注册用户数：" + userCount);
		totalMap.put("userCount", userCount);
		// 当日新增用户数
		Integer countUserRegisterToday = userService.countUserRegisterToday();
		System.out.println("当日注册用户数：" + countUserRegisterToday);
		totalMap.put("countUserRegisterToday", countUserRegisterToday);
		// 累计成交金额
		Double totalDealAmount = orderService.getTotalDealAmount();
		System.out.println("累计成交金额：" + totalDealAmount);
		totalMap.put("totalDealAmount", totalDealAmount);
		// 较昨日变动
		Double DealAmountToday = orderService.getDealAmountToday();
		System.out.println("当日成交金额：" + DealAmountToday);
		totalMap.put("DealAmountToday", DealAmountToday);
		// 累计成交商品数
		Integer totalDealProductCount = orderService.getTotalDealProductCount();
		System.out.println("累计成交商品数：" + totalDealProductCount);
		totalMap.put("totalDealProductCount", totalDealProductCount);
		// 今日成交商品数
		Integer dealProductTodayCount = orderService.getTodayDealProductCount();
		System.out.println("今日成交商品数：" + dealProductTodayCount);
		totalMap.put("dealProductTodayCount", dealProductTodayCount);

		// 累计成交用户数
		Integer dealUserCount = orderService.getDealUserCount();
		System.out.println("累计成交用户数：" + dealUserCount);
		totalMap.put("dealUserCount", dealUserCount);

		// 昨日注册用户数
		Integer registerCountYesterday = userService.countUserRegisterYesterday();
		System.out.println("昨日注册用户数：" + registerCountYesterday);
		totalMap.put("registerCountYesterday", registerCountYesterday);

		// 本周注册用户数
		Integer registerCountThisWeek = userService.countUserRegisterThisWeek();
		System.out.println("本周注册用户数：" + registerCountThisWeek);
		totalMap.put("registerCountThisWeek", registerCountThisWeek);

		// 上周注册用户数
		Integer registerCountLastWeek = userService.countUserRegisterLastWeek();
		System.out.println("上周注册用户数：" + registerCountLastWeek);
		totalMap.put("registerCountLastWeek", registerCountLastWeek);

		// 本月注册用户数
		Integer registerCountThisMonth = userService.countUserRegisterThisMonth();
		System.out.println("本月注册用户数：" + registerCountThisMonth);
		totalMap.put("registerCountThisMonth", registerCountThisMonth);

		// 上月注册用户数
		Integer registerCountLastMonth = userService.countUserRegisterLastMonth();
		System.out.println("上月注册用户数：" + registerCountLastMonth);
		totalMap.put("registerCountLastMonth", registerCountLastMonth);

		// 交易流水-当日
		Double tradingFlowToday = orderService.getTradingFlowToday();
		System.out.println("当日交易流水：" + tradingFlowToday);
		totalMap.put("tradingFlowToday", tradingFlowToday);

		// 交易流水-昨日
		Double tradingFlowYesterday = orderService.getTradingFlowYesterday();
		System.out.println("昨日交易流水：" + tradingFlowYesterday);
		totalMap.put("tradingFlowYesterday", tradingFlowYesterday);

		// 交易流水-本周
		Double tradingFlowThisWeek = orderService.getTradingFlowThisWeek();
		System.out.println("本周交易流水：" + tradingFlowThisWeek);
		totalMap.put("tradingFlowThisWeek", tradingFlowThisWeek);

		// 交易流水-本月
		Double tradingFlowThisMonth = orderService.getTradingFlowThisMonth();
		System.out.println("本月交易流水：" + tradingFlowThisMonth);
		totalMap.put("tradingFlowThisMonth", tradingFlowThisMonth);

		// 佣金收入-当日
		Double commissionRevenueToday = orderService.commissionRevenueToday();
		System.out.println("佣金收入-当日：" + commissionRevenueToday);
		totalMap.put("commissionRevenueToday", commissionRevenueToday);

		// 佣金收入-昨日
		Double commissionRevenueYesterday = orderService.commissionRevenueYesterday();
		System.out.println("佣金收入-昨日：" + commissionRevenueYesterday);
		totalMap.put("commissionRevenueYesterday", commissionRevenueYesterday);

		// 佣金收入-本周
		Double commissionRevenueThisWeek = orderService.commissionRevenueThisWeek();
		System.out.println("佣金收入-本周：" + commissionRevenueThisWeek);
		totalMap.put("commissionRevenueThisWeek", commissionRevenueThisWeek);

		// 佣金收入-本月
		Double commissionRevenueThisMonth = orderService.commissionRevenueThisMonth();
		System.out.println("佣金收入-本月：" + commissionRevenueThisMonth);
		totalMap.put("commissionRevenueThisMonth", commissionRevenueThisMonth);

		// 订单金额-当日
		Double dealAmountToday = orderService.dealAmountToday();
		System.out.println("订单金额-当日：" + dealAmountToday);
		totalMap.put("dealAmountToday", dealAmountToday);

		// 订单金额-昨日
		Double dealAmountYesterday = orderService.dealAmountYesterday();
		System.out.println("订单金额-昨日：" + dealAmountYesterday);
		totalMap.put("dealAmountYesterday", dealAmountYesterday);

		// 订单金额-本周
		Double dealAmountThisWeek = orderService.dealAmountThisWeek();
		System.out.println("订单金额-本周：" + dealAmountThisWeek);
		totalMap.put("dealAmountThisWeek", dealAmountThisWeek);

		// 订单金额-本月
		Double dealAmountThisMonth = orderService.dealAmountThisMonth();
		System.out.println("订单金额-本月：" + dealAmountThisMonth);
		totalMap.put("dealAmountThisMonth", dealAmountThisMonth);

		// 订单数-当日
		Integer dealOrderCountToday = orderService.dealOrderCountToday();
		System.out.println("订单数-当日：" + dealOrderCountToday);
		totalMap.put("dealOrderCountToday", dealOrderCountToday);

		// 订单数-昨日
		Integer dealOrderCountYesterday = orderService.dealOrderCountYesterday();
		System.out.println("订单数-昨日：" + dealOrderCountYesterday);
		totalMap.put("dealOrderCountYesterday", dealOrderCountYesterday);

		// 订单数-本周
		Integer dealOrderCountThisWeek = orderService.dealOrderCountThisWeek();
		System.out.println("订单数-本周：" + dealOrderCountThisWeek);
		totalMap.put("dealOrderCountThisWeek", dealOrderCountThisWeek);

		// 订单数-本月
		Integer dealOrderCountThisMonth = orderService.dealOrderCountThisMonth();
		System.out.println("订单数-本月：" + dealOrderCountThisMonth);
		totalMap.put("dealOrderCountThisMonth", dealOrderCountThisMonth);

		System.out.println(totalMap);
		return (HashMap<String, Object>) totalMap;
	}

	// 分页查询
	@RequestMapping("/selectAdminByCond")
	@ResponseBody
	public MyPage<?> adminSelectByCond(String Name, String Phone, int pageNum, int pageSize) {
		return adminService.adminSelectByCond(Name, Phone, pageNum, pageSize);
	}

	// 新建账户 uName uPass uEmail uPhone uIdCard userStatus accountStatus utime
	@RequestMapping("/createAdmin")
	@ResponseBody
	public String adminCreate(String aName, String aPass, String aPhone, String Jurisdiction) {
		Admin admin = new Admin();
		admin.setAdminname(aName);
		admin.setAdminpass(aPass);
		admin.setAdminphone(aPhone);
		admin.setJurisdiction(Integer.valueOf(Jurisdiction));
		String str = adminService.createAdmin(admin);
		return str;
	}

	// 查找用户，用于用户名形式唯一性验证
	@RequestMapping("/selectAdminByName")
	@ResponseBody
	public String selectAdminByName(String aName) {
		Admin admin = adminService.selectAdminByName(aName);
		return admin == null ? "false" : "true";
	}

	// 删除用户
	@RequestMapping("/deleteAdminById")
	@ResponseBody
	public String deleteAdminById(int aId) {
		int res = adminService.deleteAdminById(aId);
		return res == 1 ? "true" : "false";
	}

	// 修改用户之查找用户，跳转页面
	@RequestMapping("/goUpdateAdmin")
	public String goUpdateAdmin(String aName, Model model) {
		Admin admin = adminService.selectAdminByName(aName);
		model.addAttribute("adminuser", admin);
		return "paipai/adminiframe/updateAdmin";
	}

	// 修改用户
	@RequestMapping("/updateAdmin")
	@ResponseBody
	public String updateAdmin(int aId, String aName, String aPass, String aPhone, String Jurisdiction) {
		Admin admin = new Admin();
		admin.setAdminid(aId);
		admin.setAdminname(aName);
		admin.setAdminpass(aPass);
		admin.setAdminphone(aPhone);
		admin.setJurisdiction(Integer.valueOf(Jurisdiction));
		int res = adminService.updateAdmin(admin);
		return res == 1 ? "true" : "false";
	}

	// 普通管理员登录
	@RequestMapping("/login")
	@ResponseBody
	public String login(String adminName, String adminPass, HttpSession sess, String valideCode) {

		System.out.println("--------普通管理员登录---------------");

		// 取出系统随机给出的验证码
		String vCode = (String) sess.getAttribute("vrifyCode");
		System.out.println("系统的：" + vCode);
		System.out.println("输入的：" + valideCode);
		if (!valideCode.equals(vCode)) {
			System.out.println("验证码错误");
			return "error01";
		}

		Admin tAdmin = adminService.selectByadminNameAndadminPass(adminName, adminPass);
		if ((tAdmin == null) || (tAdmin.getJurisdiction() == 1)) {
			System.out.println("用户、密码错误");
			return "error02";
		}

		// shiro认证
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = null;
		token = new UsernamePasswordToken(adminName, adminPass);
		subject.login(token);

		sess.setAttribute("adminsession", tAdmin);
		System.out.println("--普通管理员---" + tAdmin.getAdminname());
		return "success";

	}

	// 超级管理员登录
	@RequestMapping("/logins")
	@ResponseBody
	public String logins(String adminNames, String mobile, String adminPasss, HttpSession session, String valideCodes) {

		String msg = (String) session.getAttribute("msg");
		if (!valideCodes.equals(msg)) {
			System.out.println("校验码输入错误");
			return "error01";
		}

		Admin tAdmins = adminService.selectByadminNameAndadminPass(adminNames, adminPasss);
		if ((tAdmins == null) || (tAdmins.getJurisdiction() == 0)) {
			System.out.println("用户、密码错误");
			return "error02";
		}

		// shiro认证
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(adminNames, adminPasss);
		subject.login(token);

		session.setAttribute("adminsession", tAdmins);
		System.out.println("--普通管理员---" + tAdmins.getAdminname());
		return "success";

	}

	// 短信验证
	@RequestMapping("/getMsg")
	@ResponseBody
	public Object msg(String aName, String aPass, String mobile, HttpServletResponse resp, HttpSession session) {

		Admin admin = null;
		

		admin = adminService.selectByadminNameAndadminPass(aName, aPass);
		// 获取随机字符串
		String msg = (int) ((Math.random() * 9 + 1) * 1000) + "";

		if (admin == null || !admin.getAdminphone().equals(mobile) || admin.getJurisdiction() == 0) {
		
			return "信息输入错误";
		} else {

			session.setAttribute("msg", msg);
			System.out.println(msg);
			String api = "http://v.juhe.cn/sms/send?mobile=" + mobile + "&tpl_id=188494&tpl_value=%23code%23%3d" + msg
					+ "&key=ff55f3176ca70a91101a31088836fba8";
			return rest.getForObject(api, Object.class);
		}
	}

	// 设置用户状态
	@RequestMapping("/updateShiro")
	@ResponseBody
	public String updateAccountStatus(String aName, String value) {

		Admin admin = adminService.selectAdminByName(aName);

		String str = "";
		if ("超级权限".equals(value)) {
			admin.setJurisdiction(0);
			str = "开启超级权限";
		} else {
			admin.setJurisdiction(1);
			str = "关闭超级权限";
		}

		if (adminService.updateAdmin(admin) == 1)
			return str;
		else
			return "false";

	}

	// 找回密码
	@RequestMapping("/forget")
	public String forget(String aNames, String aPass, String confirmPss, String check, HttpSession sess,
			String Codess) {
		// 图片验证码

		String vCode = (String) sess.getAttribute("vrifyCode");
		System.out.println("系统的：" + vCode);
		System.out.println("手动填写的验证码:" + Codess);

		// 短信验证updateAccountStatus
		String msgs = (String) sess.getAttribute("msg");
		System.out.println("系统发的" + msgs);
		System.out.println("手动填写的短信验证码" + check);

		Admin tAdmin = adminService.selectByadminPass1(aNames);
		System.out.println("修改之前" + tAdmin);
		if (!aNames.equals(tAdmin.getAdminname())) {
			System.out.println("该管理员不存在！");
			return "/forget";
		}
		if (!check.equals(msgs)) {
			System.out.println("短信校验码输出错误！");
			return "/forget";
		}
		if (!Codess.equals(vCode)) {
			System.err.println("图片验证码输入错误！");
			return "/forget";
		}
		if (!aPass.equals(confirmPss)) {
			System.out.println("两次输入密码不一致，请重新输入！");
			return "/forget";
		}
		System.out.println("密码修改成功，请登录");
		adminService.updateAdminPass(aPass, aNames);
		Admin tAdminx = adminService.selectByadminPass1(aNames);
		System.out.println("修改之后" + tAdminx);
		return "redirect:/";
	}

}